<!-- components/ChatSenderBar.vue -->
<template>
  <Sender
    :placeholder="placeholderText"
    :value="value"
    class="!shadow-md !w-2/3 max-w-[800px] mx-auto mb-10"
    :loading="loading"
    @submit="onSubmit"
    @change="onChange"
    @cancel="onCancel"
    :on-paste-file="pastFile"
    :actions="false"
    ref="senderRef"
  >
    <!-- header 插槽：附件上传 -->
    <template #header>
      <Sender.Header
        title="附件"
        :styles="{ content: { padding: 0 } }"
        :open="open"
        :on-open-change="(v) => (open = v)"
        force-render
      >
        <Attachments
          accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx"
          ref="attachmentsRef"
          :before-upload="() => false"
          :items="files"
          :on-change="onFileChange"
          :placeholder="getPlaceholder"
        />
      </Sender.Header>
    </template>

    <!-- footer 插槽：场景选择 + 按钮 -->
    <template
      #footer="{
        info: {
          components: { SendButton, LoadingButton, SpeechButton },
        },
      }"
    >
      <Flex justify="space-between" align="center">
        <Flex gap="small" align="center">
          <Button type="text" :icon="badgeNode" />
          <Popover v-model:open="sceneVisible" trigger="click" :arrow="false">
            <template #content>
              <ul class="min-w-[120px] p-0 m-0">
                <li
                  v-for="item in sceneList"
                  :key="item"
                  class="list-none px-4 py-2 cursor-pointer hover:bg-zinc-100 rounded-md transition"
                  @click="selectScene(item)"
                >
                  {{ item }}
                </li>
              </ul>
            </template>
            <Button
              type="text"
              class="flex items-center justify-center gap-1"
              :class="{ 'animate-highlight': sceneHighlight }"
            >
              <svg-icon name="toolbar" />
              {{ scene || '场景' }}
            </Button>
          </Popover>
        </Flex>

        <Flex align="center">
          <component :is="SpeechButton" class="mr-2" />
          <component :is="LoadingButton" v-if="loading" type="default" />
          <Tooltip v-else :title="value ? '发送 ⏎' : '请输入点什么'">
            <component :is="SendButton" type="primary" :disabled="!value" />
          </Tooltip>
        </Flex>
      </Flex>
    </template>
  </Sender>
</template>

<script setup lang="ts">
import { ref, h, computed } from 'vue'
import { Button, Flex, Tooltip, Popover, message, Badge } from 'ant-design-vue'
import { Attachments, Sender } from 'ant-design-x-vue'
import { LinkOutlined, CloudUploadOutlined } from '@ant-design/icons-vue'

// ============ Props / Emits ============
defineProps<{
  value: string
  loading: boolean
}>()

const emit = defineEmits<{
  (e: 'update:value', val: string): void
  (e: 'submit', val: string): void
  (e: 'cancel', scene: string): void
  (e: 'paste-file', files: File[]): void
}>()

const scene = defineModel('scene')
// ============ 状态 ============
const files = ref<any[]>([])
const open = ref(false)
const senderRef = ref<InstanceType<typeof Sender> | null>(null)
const attachmentsRef = ref()
const placeholderText = '请输入您的问题...'

const sceneVisible = ref(false)
const sceneHighlight = ref(false)
// const scene = ref('')
const sceneList = ['业务知识', '单价风控', '品牌识别', '制单审核', '申报要素']

// ============ 方法 ============
const onChange = (val: string) => emit('update:value', val)
const onCancel = () => {
  console.log('🐯 ~ onCancel ~ scene:', scene.value)
  emit('cancel', scene.value)
}

// 修改提交方法
const onSubmit = (val: string) => {
  if (!scene.value) {
    message.error('请先选择一个场景后再发送')
    sceneHighlight.value = true
    setTimeout(() => {
      sceneHighlight.value = false
    }, 1000)
    sceneVisible.value = true
    return
  }
  emit('submit', { content: val, files: files.value, scene: scene.value })
  files.value = []
  open.value = false // 关闭附件面板
}

const onFileChange = ({ fileList }) => {
  // 定义允许的文件类型
  const allowedTypes = {
    // 图片类型
    'image/jpeg': '图片',
    'image/png': '图片',
    'image/gif': '图片',
    // PDF类型
    'application/pdf': 'PDF',
    // Word文档类型
    'application/msword': 'Word',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word',
    // Excel类型
    'application/vnd.ms-excel': 'Excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel',
  }

  files.value = [] // 先清空

  fileList.forEach((file) => {
    const raw = file.originFileObj
    if (!raw) return

    if (!allowedTypes[file.type]) {
      message.error(`不支持的文件类型：${file.name}，仅支持图片、PDF、Word、Excel文件`)
      return
    }

    if (raw && file.type?.startsWith('image/')) {
      // 处理图片文件
      const reader = new FileReader()
      reader.onload = () => {
        file.url = reader.result as string
        file.thumbUrl = reader.result as string
        files.value.push(file)
      }
      reader.readAsDataURL(raw)
    } else {
      // 非图片文件直接添加
      files.value.push(file)
    }
  })
}

const selectScene = (item: string) => {
  sceneVisible.value = false
  scene.value = item
}

// 上传区域提示语
const getPlaceholder = (type) =>
  type.type === 'drop'
    ? {
        title: '拖动文件到这里',
        description: '支持图片、PDF、Word、Excel文件',
      }
    : {
        icon: h(CloudUploadOutlined),
        title: '上传文件',
        description: '支持图片、PDF、Word、Excel文件',
      }

const pastFile = (_, files) => {
  console.log('past')
  for (const file of files) {
    attachmentsRef.value?.upload(file)
  }
  open.value = true
}

const badgeNode = computed(() =>
  h(
    Badge,
    { dot: files.value.length > 0 && !open.value },
    {
      default: () =>
        h(Button, {
          onClick: () => (open.value = !open.value),
          icon: h(LinkOutlined),
        }),
    },
  ),
)
</script>

<style lang="scss" scoped>
.animate-highlight {
  animation: flash-border 0.3s ease-in-out 3;
}

@keyframes flash-border {
  0%,
  100% {
    box-shadow: 0 0 0px rgba(255, 0, 0, 0);
  }
  50% {
    box-shadow: 0 0 8px rgba(255, 0, 0, 1);
  }
}
</style>
